<template>
	<view class="record-list-container">
		<!-- 顶部统计区域 -->
		<view class="statistics-card">
			<view class="card-header">
				<text class="header-title">血糖统计</text>
				<text class="header-subtitle">管理和了解您的血糖变化</text>
			</view>
			
			<view class="date-filter">
				<view class="filter-item" 
					v-for="(item, index) in dateFilters" 
					:key="index"
					:class="{ active: currentDateFilter === item.value }"
					@tap="changeFilter(item.value)"
				>
					{{ item.label }}
				</view>
			</view>
			
			<view class="stat-content">
				<view class="stat-item">
					<view class="stat-value" :class="getAverageClass(statistics.average)">{{ statistics.average.toFixed(1) || '0.0' }}</view>
					<view class="stat-label">平均值 (mmol/L)</view>
				</view>
				<view class="stat-divider"></view>
				<view class="stat-item">
					<view class="stat-value" :class="getValueClass(statistics.max)">{{ statistics.max.toFixed(1) || '0.0' }}</view>
					<view class="stat-label">最高值 (mmol/L)</view>
				</view>
				<view class="stat-divider"></view>
				<view class="stat-item">
					<view class="stat-value" :class="getValueClass(statistics.min)">{{ statistics.min.toFixed(1) || '0.0' }}</view>
					<view class="stat-label">最低值 (mmol/L)</view>
				</view>
			</view>
			
			<view class="stat-reference">
				<view class="reference-item normal">
					<view class="dot"></view>
					<text>正常(3.9-6.1)</text>
				</view>
				<view class="reference-item medium">
					<view class="dot"></view>
					<text>偏高(6.1-7.8)</text>
				</view>
				<view class="reference-item high">
					<view class="dot"></view>
					<text>过高(大于7.8)</text>
				</view>
				<view class="reference-item low">
					<view class="dot"></view>
					<text>过低(小于3.9)</text>
				</view>
			</view>
		</view>
		
		<!-- 记录列表 -->
		<view class="record-list">
			<view class="list-header">
				<text class="list-title">记录列表 ({{ filteredRecords.length }}条)</text>
				<view class="action-buttons">
					<button class="refresh-btn" @tap="refreshRecords">
						<t-icon name="refresh" size="28" color="#8cc9a1"></t-icon>
					</button>
					<button class="add-btn" @tap="goToAddRecord">+ 添加</button>
				</view>
			</view>
			
			<!-- 记录分组 -->
			<block v-if="recordGroups.length > 0">
				<view class="record-group" v-for="(group, groupIndex) in recordGroups" :key="groupIndex">
					<view class="group-date">{{ formatDate(group.date) }}</view>
					
					<view class="record-item" v-for="(item, itemIndex) in group.records" :key="item.id" 
						@tap="viewRecordDetail(item)" 
						@longpress="showActionMenu(item)">
						<view class="record-time-type">
							<text class="record-time">{{ item.time }}</text>
							<text class="record-type">{{ item.typeText || getTimeTypeText(item.type) }}</text>
						</view>
						
						<view class="record-value-container">
							<text class="record-value" :class="getValueClass(item.value)">{{ isValidNumber(item.value) ? Number(item.value).toFixed(1) : '0.0' }}</text>
							<text class="record-unit">mmol/L</text>
						</view>
					</view>
				</view>
			</block>
			
			<!-- 空状态 -->
			<view class="empty-state" v-if="recordGroups.length === 0">
				<t-icon name="info-circle" size="60" color="#cccccc"></t-icon>
				<view class="empty-text">暂无血糖记录</view>
				<button class="add-record-btn" @tap="goToAddRecord">立即添加</button>
			</view>
		</view>
	</view>
	<custom-tabbar></custom-tabbar>
</template>

<script setup>
	import { ref, reactive, onMounted, computed } from 'vue'
	import { useBloodSugarStore } from '@/store/pinia.js'
	import { getRecords, deleteRecord, getMeasureTypeText } from '@/common/api/record.js'
	import { storeToRefs } from 'pinia'
	import { getBloodSugarStore, syncStorageToStore } from '@/common/utils/store-helper.js'
	import { onShow } from '@dcloudio/uni-app'
	import dataSyncService from '@/common/services/dataSync.js'
	
	// 确保__route__存在
	if (typeof __route__ === 'undefined') {
		try {
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			// @ts-ignore
			global.__route__ = currentPage.route;
		} catch (e) {
			console.error('获取当前页面路径失败:', e);
			// @ts-ignore
			global.__route__ = '/pages/record/list';
		}
	}
	
	// 使用Pinia状态管理
	const bloodSugarStore = ref(null)
	const records = ref([])
	
	// 监听页面显示
	onShow(async () => {
		console.log('血糖记录列表 onShow 触发')
		await getBloodSugarRecords()
		calculateStatistics()
		
		// 检查数据一致性，尝试同步本地记录
		try {
			// dataSyncService.checkDataConsistency()
		} catch (e) {
			console.error('数据一致性检查失败:', e)
		}
	})
	
	// 加载所有数据
	const loadData = async () => {
		await getBloodSugarRecords()
		calculateStatistics()
	}
	
	// 获取血糖记录
	const getBloodSugarRecords = async () => {
		try {
			// 先尝试从Pinia store获取
			const store = getBloodSugarStore();
			if (store) {
				bloodSugarStore.value = store;
				const storeRecords = storeToRefs(store).records;
				if (storeRecords.value && storeRecords.value.length > 0) {
					records.value = [...storeRecords.value]; // 使用展开运算符创建副本
				} else {
					// 如果 Pinia 为空，尝试从本地存储加载
					records.value = uni.getStorageSync('bloodSugarRecords') || [];
				}
			} else {
				// 如果 Pinia store 不可用，从本地存储加载
				records.value = uni.getStorageSync('bloodSugarRecords') || [];
			}

			// 调用API从服务器获取最新数据
			uni.showLoading({ title: '同步数据中...' });
			const serverResult = await getRecords(); // 直接调用 API 中的 getRecords
			if (serverResult.code === 0 && serverResult.data) {
				// 处理嵌套数据结构，从response.data.records或response.data中提取记录
				const serverRecords = serverResult.data.records || serverResult.data;
				
				// 处理每条记录，确保日期时间格式一致
				const processedRecords = serverRecords.map(record => {
					// 如果记录包含measureTime数组，转换为date和time字符串
					if (record.measureTime && Array.isArray(record.measureTime)) {
						const [year, month, day, hour, minute] = record.measureTime;
						const paddedMonth = String(month).padStart(2, '0');
						const paddedDay = String(day).padStart(2, '0');
						const paddedHour = String(hour).padStart(2, '0');
						const paddedMinute = String(minute).padStart(2, '0');
						
						return {
							...record,
							date: `${year}-${paddedMonth}-${paddedDay}`,
							time: `${paddedHour}:${paddedMinute}`,
							// 确保测量类型也被正确处理
							typeText: typeof record.measureType === 'number' ? 
								getMeasureTypeText(record.measureType) : record.typeText || '未知'
						};
					}
					return record;
				});
				
				// 更新 Pinia store (如果可用)
				if (bloodSugarStore.value) {
					bloodSugarStore.value.setRecords(processedRecords);
				}
				
				// 更新本地缓存
				uni.setStorageSync('bloodSugarRecords', processedRecords);
				
				// 更新当前页面显示的 records
				records.value = [...processedRecords];

				console.log('从服务器获取血糖记录成功:', processedRecords.length);
			} else {
				console.warn('从服务器获取血糖记录失败或无数据:', serverResult.message);
				// 如果服务器获取失败，仍然使用本地/Pinia的数据
			}
		} catch (error) {
			console.error('获取血糖记录过程中发生错误:', error);
			// 出错时，确保 records.value 仍然是数组，避免渲染错误
			if (!Array.isArray(records.value)) {
				records.value = [];
			}
		} finally {
			uni.hideLoading();
		}
	};
	
	// 日期筛选
	const currentDateFilter = ref('week')
	const dateFilters = [
		{ label: '日', value: 'day' },
		{ label: '周', value: 'week' },
		{ label: '月', value: 'month' },
		{ label: '全部', value: 'all' }
	]
	
	// 统计数据
	const statistics = reactive({
		average: 0,
		max: 0,
		min: 0
	})
	
	// 根据日期筛选条件过滤记录
	const filteredRecords = computed(() => {
		// 确保records.value是一个数组
		if (!records.value || !Array.isArray(records.value) || records.value.length === 0) {
			return []
		}
		
		const now = new Date()
		let startDate = null
		
		switch (currentDateFilter.value) {
			case 'day':
				// 今天
				startDate = new Date().toISOString().split('T')[0]
				return records.value.filter(record => record && record.date === startDate)
				
			case 'week':
				// 本周（过去7天）
				startDate = new Date(now - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
				return records.value.filter(record => record && record.date && new Date(record.date) >= new Date(startDate))
				
			case 'month':
				// 本月（过去30天）
				startDate = new Date(now - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
				return records.value.filter(record => record && record.date && new Date(record.date) >= new Date(startDate))
				
			case 'all':
			default:
				// 全部
				return records.value
		}
	})
	
	// 记录按日期分组
	const recordGroups = computed(() => {
		// 确保filteredRecords.value是一个数组
		if (!filteredRecords.value || !Array.isArray(filteredRecords.value) || filteredRecords.value.length === 0) {
			return []
		}
		
		const groups = []
		const dateMap = {}
		
		// 按日期分组
		filteredRecords.value.forEach(record => {
			// 跳过无效记录
			if (!record) return
			
			// 处理可能没有date字段的情况，尝试从measureTime中获取
			let recordDate = record.date
			
			// 如果没有date但有measureTime数组
			if (!recordDate && record.measureTime && Array.isArray(record.measureTime) && record.measureTime.length >= 3) {
				const [year, month, day] = record.measureTime
				recordDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
			}
			
			if (!recordDate) return // 如果还是没有日期，跳过
			
			if (!dateMap[recordDate]) {
				dateMap[recordDate] = []
			}
			
			// 处理可能没有time字段的情况
			let recordTime = record.time
			if (!recordTime && record.measureTime && Array.isArray(record.measureTime) && record.measureTime.length >= 5) {
				const [_, __, ___, hour, minute] = record.measureTime
				recordTime = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
			}
			
			// 构建完整记录
			const fullRecord = {
				...record,
				date: recordDate,
				time: recordTime || '00:00'
			}
			
			dateMap[recordDate].push(fullRecord)
		})
		
		// 将分组转为数组并排序
		Object.keys(dateMap).sort((a, b) => new Date(b) - new Date(a)).forEach(date => {
			groups.push({
				date,
				records: dateMap[date].sort((a, b) => {
					// 修改日期格式从 "yyyy-MM-dd HH:mm" 改为 "yyyy-MM-ddTHH:mm:ss"
					if (!a.date || !a.time || !b.date || !b.time) return 0 // 处理无效数据
					const dateA = `${a.date}T${a.time}:00`;
					const dateB = `${b.date}T${b.time}:00`;
					return new Date(dateA) - new Date(dateB);
				})
			})
		})
		
		return groups
	})
	
	// 生命周期钩子
	onMounted(async () => {
		console.log('血糖记录列表 onMounted');
		await getBloodSugarRecords(); // 等待记录加载完成
		calculateStatistics();
	})
	
	// 格式化日期
	const formatDate = (dateStr) => {
		// 如果dateStr是数组(measureTime)，转换为日期字符串
		if (Array.isArray(dateStr) && dateStr.length >= 3) {
			const [year, month, day] = dateStr;
			dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
		}
		
		try {
			const date = new Date(dateStr)
			const today = new Date().toISOString().split('T')[0]
			const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0]
			
			if (dateStr === today) {
				return '今天'
			} else if (dateStr === yesterday) {
				return '昨天'
			} else {
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${month}月${day}日`
			}
		} catch (e) {
			console.error('日期格式化错误:', e)
			return dateStr || '未知日期'
		}
	}
	
	// 切换日期筛选
	const changeFilter = (filter) => {
		currentDateFilter.value = filter
		calculateStatistics()
	}
	
	// 刷新记录
	const refreshRecords = async () => {
		console.log('手动刷新血糖记录...');
		await getBloodSugarRecords(); // 调用包含API请求的函数
		calculateStatistics(); // 重新计算统计
		uni.showToast({ title: '记录已刷新', icon: 'success', duration: 1500 });
	}
	
	// 计算统计数据
	const calculateStatistics = () => {
		// 确保filteredRecords.value是数组
		if (!filteredRecords.value || !Array.isArray(filteredRecords.value)) {
			console.error('filteredRecords.value不是数组或为null:', filteredRecords.value)
			statistics.average = 0
			statistics.max = 0
			statistics.min = 0
			return
		}
		
		// 如果没有记录，则统计数据都为0
		if (filteredRecords.value.length === 0) {
			statistics.average = 0
			statistics.max = 0
			statistics.min = 0
			return
		}
		
		// 过滤有效记录（确保有value字段且为数字）
		const validRecords = filteredRecords.value.filter(record => 
			record && record.value !== undefined && record.value !== null && !isNaN(Number(record.value))
		);
		
		if (validRecords.length === 0) {
			statistics.average = 0
			statistics.max = 0
			statistics.min = 0
			return
		}
		
		// 计算最大值、最小值和平均值
		let sum = 0
		let max = Number(validRecords[0].value)
		let min = Number(validRecords[0].value)
		
		validRecords.forEach(record => {
			const value = Number(record.value)
			sum += value
			max = Math.max(max, value)
			min = Math.min(min, value)
		})
		
		statistics.average = sum / validRecords.length
		statistics.max = max
		statistics.min = min
	}
	
	// 获取平均值对应的样式类
	const getAverageClass = (value) => {
		if (isNaN(value) || value === 0) return ''
		return getValueClass(value)
	}
	
	// 获取血糖值对应的样式类
	const getValueClass = (value) => {
		if (isNaN(value) || value === 0) return ''
		if (value < 3.9) return 'value-low'
		if (value > 7.8) return 'value-high'
		if (value > 6.1 && value <= 7.8) return 'value-medium'
		return 'value-normal'
	}
	
	// 获取测量类型的文本表示
	const getTimeTypeText = (type) => {
		// 如果type是字符串且已经是文本表示，直接返回
		if (typeof type === 'string' && ['空腹', '餐前', '餐后', '睡前', '随机'].includes(type)) {
			return type
		}
		
		// 如果type是数字，根据数字返回对应的文本
		if (typeof type === 'number' || !isNaN(Number(type))) {
			const typeCode = Number(type)
			switch (typeCode) {
				case 0: return '空腹'
				case 1: return '餐前'
				case 2: return '餐后'
				case 3: return '睡前'
				case 4: return '随机'
				default: return '未知'
			}
		}
		
		// 默认返回未知
		return '未知'
	}
	
	// 跳转到添加记录页面
	const goToAddRecord = () => {
		uni.navigateTo({
			url: '/pages/record/add'
		})
	}
	
	// 显示操作菜单
	const showActionMenu = (record) => {
		uni.showActionSheet({
			itemList: ['查看详情', '删除记录'],
			success: res => {
				switch (res.tapIndex) {
					case 0:
						// 查看详情
						viewRecordDetail(record)
						break
					case 1:
						// 删除记录
						confirmDeleteRecord(record)
						break
				}
			}
		})
	}
	
	// 查看记录详情
	const viewRecordDetail = (record) => {
		uni.navigateTo({
			url: `/pages/record/detail?id=${record.id}`
		})
	}
	
	// 确认删除记录
	const confirmDeleteRecord = (record) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该条血糖记录吗？',
			success: async res => {
				if (res.confirm) {
					await doDeleteRecord(record)
				}
			}
		})
	}
	
	// 执行删除记录
	const doDeleteRecord = async (record) => {
		uni.showLoading({
			title: '删除中...'
		})
		
		try {
			// 获取用户信息
			const userInfo = uni.getStorageSync('userInfo') || {}
			if (!userInfo.id) {
				throw new Error('请先登录后再操作')
			}
			
			// 调用API删除记录
			const res = await deleteRecord(record.id, userInfo.id)
			if (res.code === 0) {
				// 更新本地记录
				records.value = records.value.filter(item => item.id != record.id)
				
				// 保存到本地存储
				uni.setStorageSync('bloodSugarRecords', records.value)
				
				// 尝试更新Pinia状态
				try {
					if (bloodSugarStore.value) {
						bloodSugarStore.value.deleteRecord(record.id)
					}
				} catch (e) {
					console.error('更新store失败:', e)
				}
				
				// 重新计算统计数据
				calculateStatistics()
				
				// 提示成功
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
			} else {
				throw new Error(res.message || '删除失败')
			}
		} catch (e) {
			console.error('删除记录失败:', e)
			uni.showToast({
				title: typeof e === 'string' ? e : '删除失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	
	// 检查是否为有效数字
	const isValidNumber = (value) => {
		return !isNaN(Number(value)) && value !== null && value !== undefined
	}
</script>

<style lang="scss">
	.record-list-container {
		padding: 20rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
		
		.statistics-card {
			background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
			border-radius: 16rpx;
			padding: 30rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
			margin-bottom: 30rpx;
			overflow: hidden;
			position: relative;
			
			.card-header {
				margin-bottom: 20rpx;
				
				.header-title {
					font-size: 34rpx;
					font-weight: 600;
					color: #333;
					display: block;
				}
				
				.header-subtitle {
					font-size: 24rpx;
					color: #999;
					display: block;
					margin-top: 8rpx;
				}
			}
			
			.date-filter {
				display: flex;
				padding: 10rpx 0;
				margin-bottom: 30rpx;
				background-color: #f0f2f5;
				border-radius: 12rpx;
				
				.filter-item {
					flex: 1;
					text-align: center;
					font-size: 28rpx;
					color: #666;
					padding: 10rpx 0;
					position: relative;
					
					&.active {
						color: #8cc9a1;
						font-weight: bold;
						background-color: #ffffff;
						border-radius: 10rpx;
						box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
					}
				}
			}
			
			.stat-content {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 30rpx;
				
				.stat-item {
					flex: 1;
					text-align: center;
					
					.stat-value {
						font-size: 48rpx;
						font-weight: bold;
						color: #333;
						
						&.value-normal {
							color: #8cc9a1;
						}
						
						&.value-medium {
							color: #f0ad4e;
						}
						
						&.value-high {
							color: #d9534f;
						}
						
						&.value-low {
							color: #5bc0de;
						}
					}
					
					.stat-label {
						font-size: 24rpx;
						color: #999;
						margin-top: 10rpx;
					}
				}
				
				.stat-divider {
					width: 1rpx;
					height: 80rpx;
					background-color: #f0f0f0;
				}
			}
			
			.stat-reference {
				display: flex;
				flex-wrap: wrap;
				padding: 15rpx 0;
				font-size: 22rpx;
				border-top: 1rpx dashed #eee;
				
				.reference-item {
					display: flex;
					align-items: center;
					width: 50%;
					margin-bottom: 10rpx;
					
					.dot {
						width: 16rpx;
						height: 16rpx;
						border-radius: 50%;
						margin-right: 10rpx;
					}
					
					text {
						color: #666;
					}
					
					&.normal .dot {
						background-color: #8cc9a1;
					}
					
					&.medium .dot {
						background-color: #f0ad4e;
					}
					
					&.high .dot {
						background-color: #d9534f;
					}
					
					&.low .dot {
						background-color: #5bc0de;
					}
				}
			}
		}
		
		.record-list {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
			
			.list-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 20rpx;
				border-bottom: 1rpx solid #f0f0f0;
				
				.list-title {
					font-size: 30rpx;
					color: #333;
					font-weight: bold;
				}
				
				.action-buttons {
					display: flex;
					align-items: center;
					
					.refresh-btn {
						width: 60rpx;
						height: 60rpx;
						padding: 0;
						margin: 0;
						background-color: #f8f8f8;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 20rpx;
						
						.refresh-icon {
							color: #8cc9a1;
							font-size: 28rpx;
							font-weight: bold;
						}
					}
					
					.add-btn {
						font-size: 28rpx;
						color: #fff;
						background-color: #8cc9a1;
						border-radius: 30rpx;
						padding: 0 30rpx;
						height: 60rpx;
						line-height: 60rpx;
						margin: 0;
					}
				}
			}
			
			.record-group {
				margin-top: 20rpx;
				
				.group-date {
					font-size: 26rpx;
					color: #999;
					margin-bottom: 15rpx;
					background-color: #f8f8f8;
					display: inline-block;
					padding: 6rpx 20rpx;
					border-radius: 20rpx;
				}
				
				.record-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx;
					border-radius: 12rpx;
					margin-bottom: 15rpx;
					background-color: #f8f8f8;
					
					.record-time-type {
						display: flex;
						flex-direction: column;
						
						.record-time {
							font-size: 30rpx;
							color: #333;
							font-weight: bold;
							margin-bottom: 6rpx;
						}
						
						.record-type {
							font-size: 24rpx;
							color: #666;
							background-color: #eee;
							padding: 4rpx 16rpx;
							border-radius: 20rpx;
							display: inline-block;
						}
					}
					
					.record-value-container {
						display: flex;
						align-items: baseline;
						
						.record-value {
							font-size: 44rpx;
							font-weight: bold;
							
							&.value-normal {
								color: #8cc9a1;
							}
							
							&.value-medium {
								color: #f0ad4e;
							}
							
							&.value-high {
								color: #d9534f;
							}
							
							&.value-low {
								color: #5bc0de;
							}
						}
						
						.record-unit {
							font-size: 24rpx;
							color: #999;
							margin-left: 6rpx;
						}
					}
				}
			}
			
			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 60rpx 0;
				
				.empty-image {
					width: 200rpx;
					height: 200rpx;
					margin-bottom: 20rpx;
				}
				
				.empty-text {
					font-size: 28rpx;
					color: #999;
					margin-bottom: 30rpx;
				}
				
				.add-record-btn {
					width: 240rpx;
					height: 70rpx;
					line-height: 70rpx;
					text-align: center;
					background-color: #8cc9a1;
					color: #fff;
					font-size: 28rpx;
					border-radius: 35rpx;
				}
			}
		}
	}
</style> 